package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.clients.ItemClient;
import com.hmall.clients.UserserviceClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;

import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.UserHolder;
import com.sun.prism.impl.BaseContext;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;
    @Autowired
    private UserserviceClient userserviceClient;

    @Override
    @Transactional
    public Long order(Integer paymentType, Integer num, Long addressId, Long itemId) {
        Item item = itemClient.getById(itemId);
        Order order = new Order();
        order.setUserId(UserHolder.getTl());
        order.setTotalFee(item.getPrice() * num);
        order.setStatus(1);
        order.setPaymentType(paymentType);
        save(order);

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setNum(num);
        orderDetail.setTitle(item.getName());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetail.setItemId(itemId);
        orderDetailMapper.insert(orderDetail);
        Address address = userserviceClient.findAddressById(addressId);
        OrderLogistics orderLogistics = OrderLogistics.builder()
                .orderId(order.getId())
                .phone(address.getMobile())
                .province(address.getProvince())
                .city(address.getCity())
                .town(address.getTown())
                .contact(address.getContact())
                .street(address.getStreet())
                .build();
        orderLogisticsMapper.insert(orderLogistics);
        itemClient.stock(itemId,num);

        return order.getId();
    }
}
